import {
    Config
} from './config'

class Token {
    static tokenUrl = Config.restUrl + Config.tokenUrl;
    static refreshTokenUrl = Config.restUrl + Config.refreshTokenUrl;
    constructor() {}
    static getTokenFromServer() {
        return new Promise((resolve, reject) => {
            // 获取code
            wx.login({
                success: function (res) {
                    if (res.code) {
                        // console.log("code",res.code)
                        wx.request({
                            url: Token.tokenUrl,
                            method: 'POST',
                            data: {
                                "code": res.code,
                            },
                            success: (res) => {  
                                if (res.data.success) {
                                    wx.setStorageSync('token',res.data.data);
                                    resolve(res.data.data)
                                } else {
                                    reject(res.data)
                                }

                            },
                            fail: (err) => {
                                console.log("errtoken:",err)
                                reject(err)
                            }
                        })
                    }
                }
            })
        })

    }

    static refreshToken(){
        return new Promise((resolve, reject) => {
            wx.request({
                url: Token.refreshTokenUrl,
                method: 'POST',
                data: {
                    "refresh": wx.getStorageSync('token').refresh,
                },
                success: (res) => {  
                    if (res.data.success) {
                        let token = wx.getStorageSync('token');
                        token.access = res.data.data.access;
                        wx.setStorageSync('token',token);
                        resolve(res.data.data)
                    } else {
                        reject(res.data)
                    }

                },
                fail: (err) => {
                    reject(err)
                }
            })
        })
    }
}

export {Token};